<template>
  <v-app>
    <v-app-bar app>
      <div class="d-flex align-center">
        <v-img
          alt="TreeHole Logo"
          class="shrink mr-2"
          contain
          src="/upload/assets/talk.png"
          transition="scale-transition"
          width="50"
        />
      </div>
      <v-tabs>
        <v-tab to="/">首页</v-tab>
        <v-tab to="/search">搜索</v-tab>
        <v-tab v-show="!user.userId" to="/login">登录</v-tab>
        <v-tab v-show="!user.userId" to="/register">注册</v-tab>
        <v-tab v-show="user.userId" :to="{ path: '/u', query: { id: this.user.userId }}">
          <v-img
          alt="TreeHole Logo"
          class="shrink mr-2"
          contain
          :src="user.avatar"
          transition="scale-transition"
          width="50"
        />
        </v-tab>
        <v-tab v-show="user.userId" to="/set">信息设置</v-tab>
        <v-tab v-show="user.userId" @click="exitLogin">退出</v-tab>
      </v-tabs>
      
    </v-app-bar>

    <v-main class="light-green lighten-5">
      <router-view></router-view>
    </v-main>
  </v-app>
</template>

<script>
export default {
  name: 'App',
  data: () => ({

  }),
  computed: {
    user(){
      return this.$store.state.user
    }
  },
  created(){
    this.autoLogin()
  },
  mounted(){
    document.title= '"轻语"-树洞'
  },
  methods:{
    exitLogin(){
      const userId = this.user.userId, token = this.user.token
      
      // 发送请求，使token无效
      this.$utils.doPostAxios(this, '/api/user/exit', this.$qs.stringify({userId}), {
        headers: {token }
      }, ()=>{})

      // 从store中清除
      this.$store.commit('EXIT_LOGIN', {})
      // 从local中清除
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
    },
    autoLogin(){
      const token = localStorage.getItem('token')
      const userId = localStorage.getItem('userId')

      if(token && userId){
        // 先添加user，保证请求正常
        this.$store.commit('LOGIN_USER', {token, userId})

        this.$axios.post('/api/user/autoLogin', this.$qs.stringify({userId}),{
          headers: {token }
        }).then(r=>{
            const res = r.data;
            
            if(res.status == 200){
              // 自定义user
              const user = {
                userId,
                token,
                name: res.data.name,
                avatar: res.data.avatar,
              }

              // 登录账户  
              this.$store.commit('LOGIN_USER', user)
            }else{
              this.$store.commit('LOGIN_USER', {})
            }
        })
        .catch(Error=>{
            console.log(Error)
        })
      }else{
        localStorage.removeItem('token')
        localStorage.removeItem('userId')
      }
    }
  }
};
</script>

<style scoped>
</style>